<?php

namespace App\Http\Middleware;

use Closure;
use App\Repositories\Manage\RoleRepo;
use App\Repositories\Manage\MenuRepo;
use Illuminate\Support\Facades\URL;

class ManageMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $manageUser = session('manage_user');
        //登录检测
        if(empty($manageUser)){
            return redirect()->route('manage_login');
        }

        //获取用户菜单
        $uid = $manageUser->uid;
        $roleRepo = new roleRepo();
        $menuRepo = new MenuRepo();
        $roleId = $roleRepo->getRoleId('user_id = ?', [$uid]);
        $menuIdData = $roleRepo->getMenuId('role_id = ?', [$roleId]);
        $childMenu = $menuRepo->getUserMenu($menuIdData);
        $firstMenu = $menuRepo->getFirstMenuList();
        foreach ($firstMenu as $key => $res) {
            foreach ($childMenu as $k => $val) {
                try {
                    if ($val->group_id == $res->id) {
                        $childMenu[$k]->url = URL::route($val->url);
                        $firstMenu[$key]->childMenu[] = $childMenu[$k];
                    }
                } catch (\Exception $e) {
                    continue;
                }

            }
        }
        view()->share('userMenu', $firstMenu);
        view()->share('manage_user', $manageUser->name);
        view()->share('static_url', env('STATIC_URL'));

        return $next($request);
    }
}
